package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Transactional
@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {
    @Autowired
    private VMService vmService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TaskDetailsService taskDetailsService;
    @Autowired
    private MqttProducer mqttProducer;


    /**
     * 工单分页查询
     *
     * @param pageIndex
     * @param pageSize
     * @param innerCode
     * @param userId
     * @param taskCode
     * @param status
     * @param isRepair  是否是运维工单
     * @param start
     * @param end
     * @return
     */
    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }


    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(Long id) {

        TaskEntity taskEntity = this.getById(id);
        if (VMSystem.TASK_STATUS_CANCEL == taskEntity.getTaskStatus() || VMSystem.TASK_STATUS_FINISH == taskEntity.getTaskStatus()) {
            throw new LogicException("工单已取消,或工单已完成");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);

        this.updateById(taskEntity);

        //完成工单后,异步调用更改售货机状态
        noticeVMServiceStatus(taskEntity);


        return true;
    }

    /**
     * 工单封装与下发
     *
     * @param taskEntity
     */
    private void noticeVMServiceStatus(TaskEntity taskEntity) {
        //封装协议
        TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
        //封装工单类型
        taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
        //封装工单的售货机编号
        taskCompleteContract.setInnerCode(taskEntity.getInnerCode());


        //工单类型为补货工单
        if (VMSystem.TASK_TYPE_SUPPLY == taskEntity.getProductTypeId()) {
            //补货数据协议
            SupplyContract supplyContract = new SupplyContract();
            supplyContract.setInnerCode(taskEntity.getInnerCode());
            //查询工单详情列表
            List<TaskDetailsEntity> taskDetailsEntities = taskDetailsService.list(Wrappers.<TaskDetailsEntity>lambdaQuery()
                    .eq(TaskDetailsEntity::getTaskId, taskEntity.getTaskId()));
            //参数效验
            if (taskDetailsEntities == null || taskDetailsEntities.size() <= 0) {
                throw new LogicException("未查询到工单详情列表");
            }
            List<SupplyChannel> supplyChannels = taskDetailsEntities.stream().map(taskDetailsEntity -> {
                SupplyChannel supplyChannel = new SupplyChannel();
                BeanUtils.copyProperties(taskDetailsEntity, supplyChannel);
                supplyChannel.setChannelId(taskDetailsEntity.getChannelCode());
                supplyChannel.setCapacity(taskDetailsEntity.getExpectCapacity());
                return supplyChannel;
            }).collect(Collectors.toList());
            supplyContract.setSupplyData(supplyChannels);
            //发送协议,售货机修改货道状态
            try {
                mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC, 2, supplyContract);
            } catch (Exception e) {
                log.error("发送工单完成协议出错");
                throw new LogicException("发送工单完成协议出错");
            }

            return;
        }


        //发送消息,主题,消息级别,消息内容
        try {
            mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 2, taskCompleteContract);
        } catch (Exception e) {
            log.error("发送工单完成协议出错");
            throw new LogicException("发送工单完成协议出错");
        }
    }

    /**
     * 取消工单
     *
     * @param id
     * @param cancelVm
     * @return
     */
    @Override
    public boolean cancelTask(Long id, CancelTaskViewModel cancelVm) {


        TaskEntity taskEntity = this.getById(id);
        if (VMSystem.TASK_STATUS_CANCEL == taskEntity.getTaskStatus() || VMSystem.TASK_STATUS_FINISH == taskEntity.getTaskStatus()) {
            throw new LogicException("工单已取消,或工单已完成");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        taskEntity.setDesc(cancelVm.getDesc());
        this.updateById(taskEntity);


        //修改对应工人工单数量
        updateTaskZSet(taskEntity, -1);


        return true;
    }

    /**
     * 接受工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean accept(Long id) {
        TaskEntity taskEntity = this.getById(id);
        if (VMSystem.TASK_STATUS_CREATE != taskEntity.getTaskStatus()) {
            throw new LogicException("工单状态不是待处理");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);
        this.updateById(taskEntity);


        return true;
    }

    /**
     * 创建工单
     *
     * @param vo
     * @return
     */
    @Override
    public boolean addTask(TaskViewModel vo) {

        //根据工单类型效验售货机状态
        this.checkCreateTask(vo.getInnerCode(), vo.getProductType());
        //查询同一台设备是否有同类型未完成工单
        String innerCode = vo.getInnerCode();
        int productType = vo.getProductType();
        if (hasTask(innerCode, productType)) {
            throw new LogicException("该机器有未完成的同类型工单");
        }

        //创建工单对象
        TaskEntity taskEntity = new TaskEntity();
        //拷贝
        BeanUtils.copyProperties(vo, taskEntity);
        //生成工单编号
        String taskCode = this.generateTaskCode();
        taskEntity.setTaskCode(taskCode);
        //设置工单任务状态为代办
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);

        //设置工单创建类型为手动
        taskEntity.setCreateType(vo.getCreateType());
        //设置工单类型id
        taskEntity.setProductTypeId(vo.getProductType());
        //设置执行人姓名
        UserVO User = userService.getUser(vo.getUserId());
        if (User != null) {
            taskEntity.setUserName(User.getUserName());
        }
        //运程调用,获取售货机信息
        VmVO vmVO = vmService.getVMInfo(vo.getInnerCode());
        if (vmVO == null) {
            throw new LogicException("设备校验失败");
        }
        //设置所属区域id
        taskEntity.setRegionId(vmVO.getRegionId());
        //设置工作地点
        taskEntity.setAddr(vmVO.getNodeAddr());

        //存入订单,到数据库
        this.save(taskEntity);

        //判断工单类型,为补货
        if (VMSystem.TASK_TYPE_SUPPLY == vo.getProductType()) {
            //获取工单明细
            List<TaskDetailsViewModel> details = vo.getDetails();
            List<TaskDetailsEntity> taskDetailsEntitys = details.stream().map(detailVo -> {
                TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
                BeanUtils.copyProperties(detailVo, taskDetailsEntity);
                //设置订单id
                taskDetailsEntity.setTaskId(taskEntity.getTaskId());
                //补货详情存入数据库
                taskDetailsService.save(taskDetailsEntity);
                return taskDetailsEntity;
            }).collect(Collectors.toList());

        }

        //更新员工,工单数量
        updateTaskZSet(taskEntity, 1);


        return true;
    }

    /**
     * 获取同一天内分配的工单最少的人的Userid
     *
     * @param regionId 区域id
     * @param isRepair 是否是运维工单
     * @return
     */
    @Override
    public int getLeastUser(Long regionId, Boolean isRepair) {
        //定义员工类型为运营类
        String roleCode = "1002";
        if (isRepair) {
            //员工类型为运维类
            roleCode = "1003";

        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + regionId + "." + roleCode;
        //从redis中取出工单数最少的员工UserId
        Set<Integer> userIds = redisTemplate.opsForZSet().range(key, 0, 1);

        List<Integer> userIdsList = userIds.stream().collect(Collectors.toList());


        return userIdsList.get(0);
    }

    /**
     * 更新工单量列表
     *
     * @param taskEntity
     * @param score
     */
    private void updateTaskZSet(TaskEntity taskEntity, int score) {
        //默认为运维员工
        String roleCode = "1003";
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_SUPPLY) {
            //工单类型为运营,修改对应员工类型
            roleCode = "1002";
        }
        String key = VMSystem.REGION_TASK_KEY_PREF
                + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "." + taskEntity.getRegionId() + "." + roleCode;
        //使用redis原子增,使当前用户,工单量增加
        redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId(), score);

    }

    /**
     * 同一台设备下是否存在同类未完成的工单
     *
     * @param innerCode   售货机编号
     * @param productType 工单种类1
     * @return
     */
    private boolean hasTask(String innerCode, int productType) {
        int count = this.count(Wrappers.<TaskEntity>lambdaQuery()
                //相同售货机
                .eq(TaskEntity::getInnerCode, innerCode)
                //同类型工单
                .eq(TaskEntity::getProductTypeId, productType)
                //工单状态为未完成
                .le(TaskEntity::getTaskStatus, VMSystem.TASK_STATUS_PROGRESS));

        return count > 0;
    }

    /**
     * 生成工单编号
     *
     * @return
     */
    private String generateTaskCode() {
        //日期+序号
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));  //日期字符串
        String key = "lkd.task.code." + date; //redis key
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {//第一次取出,工单号时,为空
            //存入key.设置过期时间为1天
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
            return date + "0001";
        }
        //用0补充数字位数
        return date + Strings.padStart(
                //取出key对应的值,key原子自增=1,
                redisTemplate.opsForValue().increment(key, 1)
                        .toString(), 4, '0');
    }

    /**
     * 创建工单校验
     *
     * @param innerCode   设备编号
     * @param productType
     * @throws LogicException
     */
    private void checkCreateTask(String innerCode, int productType) throws LogicException {
        VmVO vmInfo = vmService.getVMInfo(innerCode);//根据设备编号查询设备
        if (vmInfo == null) throw new LogicException("设备校验失败");
        //如果是投放工单，状态为运营
        if (productType == VMSystem.TASK_TYPE_DEPLOY && vmInfo.getVmStatus() == VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备已在运营");
        }

        //如果是补货工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_SUPPLY && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }

        //如果是撤机工单，状态不是运营状态
        if (productType == VMSystem.TASK_TYPE_REVOKE && vmInfo.getVmStatus() != VMSystem.VM_STATUS_RUNNING) {
            throw new LogicException("该设备不在运营状态");
        }
    }

}

